package org.raymond.iworks.study.mq.rabbitmq.classic.alternate;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class DLXWorker {

    public static String DLX_QUEUE_NAME = "dlx_queue";
    public static String DLX_EXCHANGE_NAME = "dlx_ex";
    public static String DLX_ROUTING_NAME = "dlx_rk";

    /**
     * 进入死信交换机的触发条件:
     * 1, nack或reject,并且requeue为false的消息
     * 2, 过期(不包括队列过期)的消息
     * 3, 队列溢出的消息
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Connection conn = connection();
        Channel channel = conn.createChannel();

        channel.exchangeDeclare(DLX_EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        Map<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", 10*1000); // 消息过期时间,针对ready状态的消息,即还在消息队列中,才适用过期时间
        channel.queueDeclare(DLX_QUEUE_NAME, true, false, false, map);
        channel.queueBind(DLX_QUEUE_NAME, DLX_EXCHANGE_NAME, DLX_ROUTING_NAME);
        log.info("[*] Waiting for message");

        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            log.info(" [x] DLX Received {}:{}", delivery.getEnvelope().getRoutingKey(), message);
            try{
                doWork(message);
            }catch (InterruptedException e){
                log.error("{}: {} will intterrupt.", e.getMessage(), Thread.currentThread().getName());
                Thread.currentThread().interrupt();
            }finally {
                log.info(" [x] Done");
                boolean multiple = false;
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), multiple);
            }
        };

        boolean autoAck = false;
        channel.basicConsume(DLX_QUEUE_NAME, autoAck, deliverCallback, consumerTag->{});
    }

    private static void doWork(String task) throws InterruptedException {
        if(task.startsWith("interrupted")){
            Thread.currentThread().interrupt();
        }
        for (char ch: task.toCharArray()){
            if(ch=='.') Thread.sleep(1000);
        }
    }

    public static Connection connection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.125");
        factory.setPort(5672);
        factory.setUsername("cloud");
        factory.setPassword("cloud123");
        factory.setVirtualHost("/cloud");
        return factory.newConnection();
    }
}
